<?php

namespace app\controller\wmapi;

use Illuminate\Support\Facades;
use Illuminate\Support\Facades\Validator;
use plugin\admin\app\common\Util;
use plugin\admin\app\model\Admin;
use support\Request;
use app\model\WaAdmins;
use app\model\WaRoles;
use app\model\WaRules;
use app\model\WaDepartment;
use Illuminate\Support\Facades\DB;
use Tymon\JWTAuth\Facades\JWTAuth;
use Illuminate\Support\Facades\Cache;
use Tinywan\Validate\Validate;

class DepartmentController extends Validate
{
    /**
     * 部门管理 -列表-分页
     * @param Request $request
     * @return mixed
     */
    public function departmentList(Request $request)
    {
        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $condition [] = ['pid', '=', 0];
        $condition [] = ['status', '!=', 4];

        $rule = WaDepartment::list($fields, $condition);

        return IndexController::successed($rule, '部门列表');
    }

    /**
     * 部门管理 -列表-无分页
     * @param Request $request
     * @return mixed
     */
    public function departmentAll(Request $request)
    {
        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $condition [] = ['status', '!=', 4];
        $rule = WaDepartment::all($fields, $condition);
        return IndexController::successed($rule, '部门列表');
    }


    /**
     * 部门-创建
     * @param Request $request
     * @return \support\Response
     */
    public function departmentCreate(Request $request)
    {
        process($request);
        $param = $request->all();
        /**
         * 验证规则
         */
        $rule = [
            'name' => 'require|max:50', // 用户名
        ];
        $data = [
            'name' => $param['name'] ?? '', // 用户名
            'pid' => intval($param['pid']) ?? '', // 父亲id
            'created_at' => date('Y-m-d H:i:s', time()), // 创建时间
            'status' => 0, // 0 正常 1禁用 4删除 部门没有禁用 只有 删除
        ];

//        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
//        if (!$validate->check($param)) {
//            return IndexController::errored($validate->getError());
//        } else {
        $where = ['name' => $param['name'], 'status' => 0]; // 0 正常 1禁用 4删除 部门没有禁用 只有 删除
        $find = WaDepartment::find($where);
        $find = json_decode($find);
        if ($find) {
            if (property_exists($find, 'id')) {
                return IndexController::errored('', '部门创建失败,部门名称已存在');
            }
        }

        $res = WaDepartment::created($data);
        if (!$res) {
            return IndexController::errored($res, '部门创建失败');
        } else {
            return IndexController::successed($res, '部门创建成功');
        }
//        }

    }

    /**
     * 部门-更新
     * @param Request $request
     * @return \support\Response
     */
    public function departmentEdit(Request $request)
    {
        process($request);
        $param = $request->all();
        /**
         * 验证规则
         */
        $rule = [
            'name' => 'require|max:50', // 用户名
            'department_id' => 'require', // 角色id
        ];
        $data = [
            'name' => $param['name'] ?? '', // 用户名
            'pid' => intval($param['pid']) ?? '', // 父亲id
            'updated_at' => date('Y-m-d H:i:s', time()), // 创建时间
        ];


        $validate = \Tinywan\Validate\Facade\Validate::rule($rule);
        if (!$validate->check($param)) {
            return IndexController::errored($validate->getError());
        } else {
            $where = ['name' => $param['name']];
            $find = WaDepartment::find($where);
            $find = json_decode($find);
            if ($find) {
                if (property_exists($find, 'id')) {
                    if ($param['name'] != $find->name) {
                        return IndexController::errored('', '部门更新失败,部门已存在');
                    }
                }
            }

            $condition = [];
            $condition [] = ['id', '=', intval($param['department_id'])];
            $res = WaDepartment::updated($condition, $data);
            if (!$res) {
                return IndexController::errored($res, '部门更新失败');
            } else {
                return IndexController::successed($res, '部门更新成功');
            }
        }
    }

    /**
     * 部门-删除
     * @param Request $request
     * @return \support\Response
     */
    public function departmentDel(Request $request)
    {
        process($request);
        $param = $request->all();
        $condition = [];
        $condition [] = ['id', '=', intval($param['department_id'])];
        $data = ['status' => 4]; //0 正常 1禁用 4删除 部门没有禁用 只有 删除
        // 判断是否有子部门
//        $ary = [1,4,5,6,16,38];
//        if (in_array($ary,$param['department_id'])){
//            return IndexController::errored('', '该部门无法删除');
//        }
        $department = WaDepartment::find([['pid', '=', intval($param['department_id'])], ['status', '!=', 4]]);
        $department = json_decode($department);
        if ($department) {
            return IndexController::errored('', '该部门还存在子部门无法删除');
        }

        // 判断是否有用户绑定部门
        $Admins = WaAdmins::find(['department_id' => intval($param['department_id'])]);
        $Admins = json_decode($Admins);
        if ($Admins) {
            return IndexController::errored('', '有用户绑定该部门无法删除');
        }
        $rule = WaDepartment::updated($condition, $data);
        return IndexController::successed($rule, '部门-删除成功');
    }

    /**
     * 所有部门所有人
     * @param Request $request
     * @return mixed
     */
    public function departmentAndAdminAll(Request $request)
    {
        // 菊花,金银花,枸杞,红枣,山楂,茯苓,金线莲,决明子,柠檬,牛蒡,麦冬 有何功效
        process($request);
        $param = $request->all();
        $fields = ['*'];
        $condition = [];
        $condition [] = ['pid', '=', 0];
        $condition [] = ['status', '!=', 4];
        $dep = WaDepartment::allList($fields, $condition);
        $dep = json_decode($dep);
//        get_object_vars()
        if ($dep) {
            foreach ($dep as $kd) {
                if ($kd) {
                    $admin_kd0 = self::departmentAndAdminByWhere($kd->id);
                    $kd->user = $admin_kd0; // 第一级 最高级领导
                    $secondChildren = \support\Db::table('wa_department')->where([['pid','=', $kd->id],['status','!=',4]])->get();
                    if ($secondChildren){
                        foreach ($secondChildren as $kse){
                            $kse->is_user = false;
                        }
                        $kd->children = $secondChildren;// 第二级部门


                        foreach ($secondChildren as $kth){

                            $admin_kd1 = self::departmentAndAdminByWhere($kth->id);
                            $kth->user = $admin_kd1;// 第二级部门领导

                            $thirdChildren = \support\Db::table('wa_department')->where([['pid','=', $kth->id],['status','!=',4]])->get();
                            if ($thirdChildren){
                                foreach ($thirdChildren as $kthe){
                                    $kthe->is_user = false;
                                }
                                $kth->children = $thirdChildren;
                            foreach ($thirdChildren as $kfo){
                                $admin_kd3 = self::departmentAndAdminByWhere($kfo->id);
                                $kfo->user = $admin_kd3;// 第三级普通管理员
                                $fourChildren = \support\Db::table('wa_department')->where([['pid','=', $kfo->id],['status','!=',4]])->get();
                                if ($fourChildren){
                                    foreach ($fourChildren as $foue){
                                        $foue->is_user = false;
                                    }
                                    $kfo->children = $fourChildren;
                                    foreach ($fourChildren as $kfiv){
                                        $admin_kd4 = self::departmentAndAdminByWhere($kfiv->id);
                                        $kfiv->user = $admin_kd4;// 第三级普通管理员

                                    }
                                }else{
                                    $kfo->children = [];
                                }

                                $whereIn = [];
                                $admin_arys = [];
//                                foreach ($kd->children as $kfi) { // 第三层 底层
//                                    $condition = [];
//                                    if ($admin_kd) {
////                            $whereIn = [$kd->pid,$kfi->pid,$kfi->id];
//                                        $whereIn = [$kfi->id];
//                                    } else {
//                                        $condition [] = ['department_id', '=', $kfi->id];
//                                    }
//                                    $condition [] = ['status', '=', 0];
//                                    $fields = ['id', 'nickname as name'];
//                                    $admin = WaAdmins::allIdByWhereIn($fields, $condition, $whereIn);
//                                    $admin = json_decode($admin);
//                                    $kfi->children = $admin;
//                                }
                            }



                            }else{
                                $kth->children = [];
                            }
                        }

                    }else{
                        $kd->children = [];
                    }

                } else {
                    $kd->user = [];
                }
            }
        }
        return IndexController::successed(json_encode($dep), '部门列表');
    }

    public static function departmentAndAdminByWhere($id){
        $whereIn_kd = [];
        $condition_kd = [];
        $condition_kd [] = ['department_id', '=', $id];
        $condition_kd [] = ['status', '=', 0];
        $fields_kd = ['id', 'nickname as name'];
        $admin_kd = WaAdmins::allIdByWhereIn($fields_kd, $condition_kd, $whereIn_kd);
        $admin_kd = json_decode($admin_kd);
        if($admin_kd){
            foreach ($admin_kd as $kd){
                $kd->is_user = true;
            }
        }

        return $admin_kd;
    }
}